// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import Vant, {Lazyload, Dialog, ImagePreview} from 'vant'
import 'vant/lib/index.css'
import axios from 'axios'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import VueWechatTitle from 'vue-wechat-title'
import BaiduMap from 'vue-baidu-map'
import 'styles/iconfont.css'
import 'styles/index.css'

Vue.config.productionTip = false
axios.defaults.withCredentials = true
Vue.prototype.$axios = axios
Vue.use(Lazyload, {
  error: require('./assets/img/news.png'),
  loading: require('./assets/img/news.png')
})
Vue.use(Dialog)
Vue.use(ImagePreview)
Vue.use(Vant)
Vue.use(VueWechatTitle)
Vue.use(VueAwesomeSwiper)
Vue.prototype.baseUrl = 'https://scshangpu.com'
Vue.use(BaiduMap, {
  ak: '6df8f9402d5667dd10ec312ca51e87f5'
})
// 在请求头中加token
axios.interceptors.request.use(
  config => {
  // 判断是否存在token，如果存在的话，则每个http header都加上token
    let token = sessionStorage.getItem('token')
    if (!config.headers.hasOwnProperty('token') && token) {
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)) { // 判断该路由是否需要登录权限
    let token = sessionStorage.getItem('token')
    if (token) { // 判断当前的token是否存在 ； 登录存入的token
      next()
    } else {
      next({
        path: '/login'
      })
    }
  } else {
    next()
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store: store,
  components: { App },
  template: '<App/>'
})
